package main

import (
	"encoding/csv"
	"log"
	"net/http"
	"os"
	"sync"
)

func processBatch(batchData [][]string, wg *sync.WaitGroup, tokenWriter *csv.Writer) {
	defer wg.Done()

	for _, row := range batchData {
		if len(row) < 2 {
			continue
		}

		userID := row[0]
		appUserID := row[1]

		// 发送 HTTP 请求
		resp, err := http.Post("https://gz-api-bnd.yuntiancloud.com:18113/v1/servo/usertoken", "application/json", nil)
		if err != nil {
			log.Printf("Error sending HTTP request: %v", err)
			continue
		}
		defer resp.Body.Close()

		if resp.StatusCode != http.StatusOK {
			log.Printf("HTTP request failed with status code: %d", resp.StatusCode)
			continue
		}

		// 处理响应数据
		// 这里假设响应数据中有 userid 和 token 字段
		uuid := "uuid_value"
		token := "token_value"

		// 写入 CSV 文件
		tokenWriter.Write([]string{userID, appUserID, uuid, token})
	}
}

func main() {
	inputFile, err := os.Open("output1111.csv")
	if err != nil {
		log.Fatalf("Error opening input file: %v", err)
	}
	defer inputFile.Close()

	reader := csv.NewReader(inputFile)
	records, err := reader.ReadAll()
	if err != nil {
		log.Fatalf("Error reading CSV file: %v", err)
	}

	outputFile, err := os.Create("user_token.csv")
	if err != nil {
		log.Fatalf("Error creating output file: %v", err)
	}
	defer outputFile.Close()

	tokenWriter := csv.NewWriter(outputFile)
	defer tokenWriter.Flush()

	// 并发处理数据
	var wg sync.WaitGroup
	batchSize := 100
	for i := 0; i < len(records); i += batchSize {
		end := i + batchSize
		if end > len(records) {
			end = len(records)
		}
		batchData := records[i:end]
		wg.Add(1)
		go processBatch(batchData, &wg, tokenWriter)
	}

	wg.Wait()
	log.Println("Processing completed")
}
